package com.sn.shop.filter;

import com.sn.shop.dao.RedisDao;
import com.sn.shop.enums.ResultStatus;
import com.sn.shop.utils.JwtUtil;
import com.sn.shop.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @auther sn
 * @date 2018/3/28
 * @description TODO
 */
public class AuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    RedisDao redisDao;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(JwtUtil.TOKEN);
        if (token == null || redisDao.getValue(token)==null) {
            filterChain.doFilter(request, response);
            return;
        }

        String username = JwtUtil.validateToken(token);
        if(username != null) {
            // 想办法拿到userDetails
            String userDetailsJson = redisDao.getValue(token);
            UserDetails userDetails = JwtUtil.getUserDetailsByJson(userDetailsJson);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(), userDetails.getAuthorities());
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
